<?php
namespace app\index\controller;

use think\Controller;
use think\Session;
use think\Request;

class xiaodian extends Controller{

	public function _initialize(){
		
		parent::_initialize();
		
		$shop_id = Request::instance()->param('shop_id');
        
        //echo 'b'.$shop_id . 'x'; exit;
		
		//shop_id   url param or cache or agent_id(agent)
		
		if(!IS_TEST){
		
			//1、得到真实店铺ID
			if(!\RegexHelper::is_en($shop_id)){
				if(Session::has('shop_id')){
					$shop_id = Session::get('shop_id');
				}else{
					//默认店铺ID
				}
			}
			
			//2、得到零售ID
			$cust_id = -1;
			if(Session::has('cust_id')){
				$cust_id = Session::get('cust_id');
			}else{
				if(Session::has('agent_id')){
					//代理登陆过
					$cust_id = -1;
				}else{
					//代理也没登陆过
					$this->redirect('Shoplogin/index');
				}
			}
			
			//校验shop_id
			$param = [
				'agentid'=>$shop_id, //没有则默认店铺
				'customerid'=>$cust_id, // -1=代理身份，不为空则为零售客户
			];
			
			$response = \ServerHelper::post('shop_getshopid',$param);
            __log($response,'shoplogin');
			$data = $this->J($response);
			if(empty($data['flag'])){
				$this->error('数据错误');
			}
			$shop_id = $data['data']['shopid'];
			$cust_id = $data['data']['customerid'];
		}else{
			$shop_id = $shop_id == '' ? 'AG_20200419214821465874' : $shop_id;
			$cust_id = TEST_CUSTOMER_ID;
		}
		
		//代理跨店提示
		if(Session::get('shop_id') != $shop_id){
			Session::set('cancelkdts','0');
		}
		
		//echo Session::get('shop_id') . '-' . $shop_id;

		define('SHOP_ID',$shop_id); //店铺ID 也 等于 店铺所有者的ID
		Session::set('shop_id',SHOP_ID);
		
		define('CUST_ID',$cust_id);
		Session::set('cust_id',CUST_ID);
		
	}
	
	protected function J($list){
		$data = json_decode($list,true);
		if(!isset($data['flag'])){
			exit('connect error');
		}
		return $data;
	}
	
}
